package com.shuyuansystem.service.impl;

import com.shuyuansystem.service.OrderMessageService;
import com.shuyuansystem.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

@Service
public class OrderMessageServiceImpl implements OrderMessageService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate; // 明确泛型类型为 <String, String>
    @Autowired
    private JavaMailSender sender;

    private String subject = "溯源平台邮箱验证码";
    private String content = "您的邮箱验证码是";
    private String from = "15768227055@163.com";
    // 随机生成验证码

    @Override
    public boolean sendMail(String to) throws MessagingException {
        Integer generateValidateCode = ValidateCodeUtils.generateValidateCode(6);
        // 将 Integer 类型的验证码转换为 String 类型
        String validateCodeStr = String.valueOf(generateValidateCode);

        // 把验证码存进 redis 中
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(to, validateCodeStr, 60, TimeUnit.SECONDS);

        MimeMessage mail = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mail);
        helper.setSubject(subject);
        helper.setText(content + validateCodeStr); // 使用转换后的字符串
        helper.setFrom(from);
        helper.setTo(to);
        sender.send(mail);
        System.out.println("邮件发送完毕");
        return true;
    }
}